package com.itheima.dubbo.api;

import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageResult;
import com.itheima.dubbo.util.IdSequence;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/1/30 21:09
 */
@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdSequence idSequence;

    @Override
    public String save(Video video) {
        video.setId(ObjectId.get());
        video.setVid(idSequence.getNextId("video"));
        video.setCreated(System.currentTimeMillis());

        mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    @Override
    public PageResult<Video> findVideoList(int page, int pagesize) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));

        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, videoList);
    }

    @Override
    public Video findVideoById(String videoId) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(videoId)));
        return mongoTemplate.findOne(query, Video.class);
    }

    @Override
    public PageResult<Video> findVideoList(int page, int pagesize, Long uid) {
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        List<Video> videos = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, videos);
    }

    @Override
    public List<Video> findVideoListByVidList(List<Long> vidList) {
        Query query = new Query(Criteria.where("vid").in(vidList));
        return mongoTemplate.find(query, Video.class);
    }
}
